<template>
	<div class="order_container">
		<div class="order_header">
			<el-input v-model="searList.orderNo" clearable style="width: 200px;" placeholder="请输入订单编号"></el-input>
			<el-select v-model="searList.status" style="width: 200px" placeholder="请选择订单状态">
				<el-option v-for="(key, value) in orderStatusList" :key="key" :label="key" :value="value" />
			</el-select>
			<el-button type="primary" icon="el-icon-search" @click="search" style="margin-left: 5px;">查找</el-button>
			<br />
			<el-date-picker type="datetime" v-model="downloadList.gmtStart" style="width: 200px;margin-top: 10px;"
				default-time="00:00:00" placeholder="选择开始日期" />
			至
			<el-date-picker type="datetime" v-model="downloadList.gmtEnd" style="width: 200px" default-time="00:00:00"
				placeholder="选择结束日期" />
			<el-select style="width: 200px" placeholder="待出库" v-model="downloadList.status">
				<el-option v-for="(key, value) in orderStatusList" :key="key" :label="key" :value="value" />
			</el-select>
			<el-button type="primary" icon="el-icon-download" @click="download" style="margin-left: 5px;">导出</el-button>
			<el-button type="primary" icon="el-icon-download" @click="downloadAll" style="margin-left: 5px;">汇总</el-button>
		</div>
		<!-- 数据-->
		<el-table v-loading="loading" :data="orderList" size="small" element-loading-text="正在查询中。。。" border fit
			highlight-current-row :cell-class-name="cellColor">
			<el-table-column type="expand">
				<template slot-scope="props">
					<el-form label-position="right" class="table-expand">
						<el-form-item>
							<el-form-item label="联系人">
								<span>{{ props.row.consignee }}</span>
							</el-form-item>
						</el-form-item>
					</el-form>
					<el-form label-position="right" class="table-expand">
						<el-form-item label="联系电话">
							<span>{{ props.row.phone }}</span>
						</el-form-item>
					</el-form>
					<el-form label-position="right" class="table-expand">
						<el-form-item label="客服备注">
							<span>{{ props.row.adminMono ? props.row.adminMono : "无"}}</span>
						</el-form-item>
					</el-form>
					<el-form label-position="right" class="table-expand"
						v-if="props.row.status === 60 || props.row.refundReason">
						<el-form-item label="退款原因">
							<span>{{props.row.refundReason? props.row.refundReason: "未填写退款原因"}}</span>
						</el-form-item>
					</el-form>
				</template>
			</el-table-column>
			<el-table-column align="center" width="180" label="订单编号" prop="orderNo" />

			<el-table-column align="center" width="80" label="用户ID" prop="userId" />

			<el-table-column align="center" width="120" label="订单状态" prop="status">
				<template slot-scope="scope">
					<el-tag>{{ fixOrderStatus(scope.row.status) }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" width="110" label="支付渠道" prop="payChannel">
				<template slot-scope="scope">
					<el-tag>{{payPosition(scope.row.payChannel)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" width="100" label="订单金额" prop="actualPrice">
				<template slot-scope="scope">¥ {{ scope.row.actualPrice / 100.0 }}</template>
			</el-table-column>
			<el-table-column align="center" width="100" label="订单金额" prop="actualPrice">
				<template slot-scope="scope">¥ {{ scope.row.actualPrice / 100.0 }}</template>
			</el-table-column>
			<el-table-column align="center" width="140" label="创建时间" prop="gmtCreate">
				<template slot-scope="scope">{{createTime(scope.row.gmtCreate)}}</template>
			</el-table-column>
			<el-table-column align="center" width="140" label="物流渠道" prop="shipCode">
				<template slot-scope="scope">
					<el-tag>{{ fixLogistics(scope.row.shipCode)}}</el-tag>
				</template>
			</el-table-column>
			<el-table-column align="center" width="200" label="物流单号" prop="shipNo" />
			<el-table-column align="center" width="200" label="备注" prop="mono" />

			<el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button type="primary" size="mini" @click='detailBtn(scope.row)'>详情</el-button>
					<el-button v-if="scope.row.status === 20" type="primary" size="mini" @click='dispatchin(scope.row)'>配送单</el-button>
					<el-button v-if="scope.row.status === 20" type="primary" size="mini" @click='shipBtn(scope.row)'>发货</el-button>
					<el-button v-if="scope.row.status === 60" type="primary" size="mini" @click='refund(scope.row)'>退款</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 详情弹框 -->
		<el-dialog title="订单详情" :visible.sync="detailDialogVisible">
			<el-form :data="detailFrom" label-position="left" width="800">
				<el-form-item label="订单编号">
					<span>{{detailFrom.orderNo}}</span>
				</el-form-item>
				<el-form-item label="用户Id">
					<span>{{detailFrom.userId}}</span>
				</el-form-item>
				<el-form-item label="订单渠道">
					<span>{{detailFrom.channel}}</span>
				</el-form-item>
				<el-form-item label="订单状态">
					<el-tag>{{fixOrderStatus(detailFrom.status)}}</el-tag>
				</el-form-item>
				<el-form-item label="支付渠道">
					<el-tag>{{payPosition(detailFrom.payChannel)}}</el-tag>
				</el-form-item>
				<el-form-item label="用户留言">
					<span>{{detailFrom.mono}}</span>
				</el-form-item>
				<el-form-item label="客服备注">
					<span style="margin-right: 10px;">{{detailFrom.adminMono}}</span>
					<el-button type="primary" icon="el-icon-edit" @click='fixAdminMono()'>编辑</el-button>
				</el-form-item>
				<el-form-item label="配送费用">
					<span>{{detailFrom.freightPrice>0?(detailFrom.freightPrice/100.0):"免运费"}}</span>
				</el-form-item>
				<el-form-item label="收货信息">
					<span
						class="messagae">(收货人){{detailFrom.consignee}}(手机号){{detailFrom.phone}}(地址){{detailFrom.province}}
						{{detailFrom.city}} {{detailFrom.county}} {{detailFrom.address}}</span>
				</el-form-item>
				<el-form-item label="商品信息" label-width="100%">
					<el-table :data="detailFrom.skuList" size="small" border fit highlight-current-row
						style="width: 668px;">
						<el-table-column align="center" label="名称" prop="spuTitle" />
						<el-table-column align="center" label="规格" prop="title" />
						<el-table-column align="center" label="商品数量" prop="num" />
						<el-table-column align="center" label="单位" prop="unit" />
						<el-table-column align="center" label="总价（单价*数量）">
							<template slot-scope="scope">
								<span>{{ (scope.row.price * scope.row.num) / 100 }}</span>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
			</el-form>
		</el-dialog>
		<el-dialog title="发货" :visible.sync="adminMonoVisible">
			<el-form label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
				<el-form-item label="等级" prop="adminMonoLevel">
					<el-radio-group v-model="detailFrom.adminMonoLevel">
						<el-radio :label="0">无色</el-radio>
						<el-radio :label="1">绿色</el-radio>
						<el-radio :label="2">橙黄</el-radio>
						<el-radio :label="3">红色</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="内容" prop="adminMono">
					<el-input v-model="adminMono"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeAdminMonoDialog()">取消</el-button>
				<el-button type="primary" @click="updateAdminMono()">确定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="发货" :visible.sync="shipVisible">
			<el-form status-icon label-position="left" :rules="shipRules" label-width="100px" style="width: 400px; margin-left:50px;" ref="shipForm" :model="shipForm"> 
				<el-form-item label="快递公司"  prop="shipCode">
					<el-select v-model="shipForm.shipCode" style="width: 200px" placeholder="请选择订单状态">
						<el-option v-for="(key, value) in logistics" :key="key" :label="key" :value="value" />
					</el-select>
				</el-form-item>
				<el-form-item label="快递编号" prop="shipNo">
					<el-input v-model="shipForm.shipNo" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeshipDialog()">取消</el-button>
				<el-button type="primary" @click="sendShip()">确定</el-button>
			</div>
		</el-dialog>
		<el-dialog title="退款" :visible.sync="refundVisible">
			<el-form :data='refund' :ref="refund" label-width="100px" label-position='left' style="margin-left: 50px;">
				<el-form-item label="tips">
					<span>允许退款后钱会退回对方账户，请确认您已经收到退货</span>
				</el-form-item>
				<el-form-item label="操作">
					<el-radio v-model="refundForm.type" label="0">拒绝退款</el-radio>
					<el-radio v-model="refundForm.type" label="1">允许退款</el-radio>
				</el-form-item>
				<el-form-item v-if="refundForm.type === '1'" label="金额">
					<el-input v-model="refundForm.sum" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeRetfundDialog()">取消</el-button>
				<el-button  type="primary" @click="confirmRefund">确定</el-button>
			</div>
		</el-dialog>
		<!-- 分页 -->
		<el-footer v-if="orderList.length>0" class="border-top d-flex align-items-center px-0  bg-white"
			style="margin-top: 36px;">
			<div style="flex: 1;" class="px-2">
				<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
					:current-page.sync="searList.pageNo" :page-sizes="[10, 20, 30, 50, 100]" :page-size="searList.limit"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>
		</el-footer>
	</div>
</template>

<script>
	import {
		getOrderList,
		getOrderDetail,
		editAdminMono,
		ship,
		setRefund,
		queryToExcel,
		statisticsToExcel
	} from '../api.js'
	let orderStatusList = {
		10: "未付款",
		12: "正在拼团",
		20: "待出库",
		30: "待收货",
		40: "待评价",
		50: "已完成",
		60: "退款中",
		70: "已退款",
		80: "已取消",
		90: "已取消(系统)"
	};
	let pay = {
		WX: "微信支付",
		ALI: "支付宝",
		OFFLINE: "线下支付"
	}
	let logistics = {
		NONE: "无需物流公司",
		ZTO: "中通快递", 
		STO: "申通快递",
		HTKY: "百世快递",
		SF: "顺丰速运",
		YTO: "圆通速递",
		YZPY: "邮政快递包裹",
		YD: "韵达速递",
		ZJS: "宅急送",
		EMS: "EMS",
		HHTT: "天天快递",
		JD: "京东快递",
		UC: "优速快递",
		DBL: "德邦快递",
		TNT: "TNT快递",
	}
	export default {
		data() {
			return {
				// 搜索和获取数据对象
				searList: {
					orderNo: undefined,
					status: undefined,
					page: 1,
					limit: 20
				},
				total: 1,
				loading: false, //加载
				orderList: [], //订单列表
				orderStatusList, //订单状态
				pay,
				logistics,
				downloadList: {
					gmtStart: undefined,
					gmtEnd: undefined,
					status: ""
				},
				detailDialogVisible: false, //详情
				adminMonoVisible: false, //客服编辑
				shipVisible:false,//发货
				refundVisible:false,//退款
				adminMono: "",
				detailFrom: {} ,//详情表单
				shipForm:{//发货表单
					orderNo: undefined,
					shipCode: "NONE",
					shipNo: undefined
				},
				refundForm:{//退款表单
					orderNo:undefined,
					type:'0',
					sum:undefined
				},
				shipRules:{
					shipCode: [{
						required: true,
						message: "请选择物流类型",
						trigger: "blur"
					}]
				}
			}
		},
		methods: {
			// 获取数据
			getData() {
				this.loading = true;
				getOrderList(this.searList).then((res) => {
					// console.log(res)
					this.orderList = res.data.data.items;
					this.total = res.data.data.total;
					this.loading = false;
				})
			},
			handleSizeChange(val) { //每页条数
				this.searList.limit = val
				this.getData();
			},
			handleCurrentChange(val) { //前往第几页
				this.searList.page = val
				// console.log(val)
				this.getData()
			},
			// 搜索
			search() {
				this.searList.page = 1;
				this.getData();
			},
			// 状态过滤
			fixOrderStatus(status) {
				return orderStatusList[status];
			},
			// 支付渠道的过滤
			payPosition(value) {
				if (pay[value]) {
					return pay[value];
				}
				return "未支付"
			},
			// 物流渠道的过滤
			fixLogistics(value) {
				if (logistics[value]) {
					return logistics[value];
				}
				return "未发货";
			},
			// 创建时间
			createTime(value) {
				if (value) {
					var date = new Date(value); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
					var M = date.getMonth() + 1 + '月';
					var D = date.getDate() + '日';
					var h = date.getHours() + '时';
					var m = date.getMinutes() + '分';
					return M + D + h + m;
				} else {
					return '无'
				}
			},
			// 详情
			detailBtn(value) {
				this.detailDialogVisible = true;
				getOrderDetail(value.id).then((res) => {
					console.log(res.data.data)
					this.detailFrom = res.data.data
				})
			},
			// 客服编辑
			fixAdminMono() {
				this.adminMonoVisible = true;
				this.adminMono = this.detailFrom.adminMono;//赋值给input
			},
			// 修改客服
			updateAdminMono(){
				this.detailFrom.adminMono = this.adminMono;
				editAdminMono(this.detailFrom.id, this.detailFrom.adminMonoLevel, this.detailFrom.adminMono).then((res) => {
					// console.log(res)
					this.$message.success("客户备注成功！")
					this.adminMonoVisible = false;
					this.getData()//刷新数据
				})
			},
			// 关闭客服编辑弹出框
			closeAdminMonoDialog() {
				this.adminMonoVisible = false;
			},
			// name	单元格的 className 的回调方法
			cellColor({row, column, rowIndex, columnIndex}) {
				if (columnIndex === 1) {//第一个单元格
					if (row.adminMonoLevel) {//备注等级是否存在
						if (row.adminMonoLevel === 1) {//备注等级等级为1
							return "green";
						} else if (row.adminMonoLevel === 2) {//等级为2
							return "orange";
						} else if (row.adminMonoLevel === 3) {//等级为3
							return "red";
						}
					}
					return "";
				}
			},
			// 发货
			shipBtn(value){
				this.shipVisible = true;
				console.log(value)
				this.shipForm.orderNo = value.orderNo;
				if (this.$refs.shipForm != undefined) { //移除验证
					this.$refs.shipForm.resetFields();
				}
			},
			sendShip(){
				this.$refs["shipForm"].validate(valid => {
					if (valid) {
						if(this.shipForm.shipCode != 'NONE' && this.shipForm.shipNo === undefined ||this.shipForm.shipNo ==='' ){
							this.$message.error('请填写运单号')
						}else{
							ship(this.shipForm).then((res)=>{
								console.log(res)
								this.shipVisible = false;
								this.$message.success('确认发货成功！')
								this.getData()
							})
							.catch((msg) => {
								this.shipVisible = false;
								this.$message.error(msg.data.data.errmsg)
							})
						}
					}else{
						return false;
					}
					})
				
			},
			// 关闭发货弹出框
			closeshipDialog(){
				this.shipVisible = false;
			},
			// 退款
			refund(value){
				// console.log(value)
				this.refundVisible = true;
				this.refundForm.orderNo = value.orderNo;
				this.refundForm.sum = (value.actualPrice) / 100.0 
			},
			// 确认退款
			confirmRefund(){
				this.refundForm.sum = this.refundForm.sum*100
				// console.log(this.refundForm)
				setRefund(this.refundForm).then((res)=>{
					console.log(res);
					this.refundVisible = false;
					this.$message.success("退款成功！")
					this.getData();
					
				})
			},
			// 关闭退款弹框
			closeRetfundDialog(){
				this.refundVisible = false;
			},
			// 配送单
			dispatchin(value){
				// console.log(value)
				getOrderDetail(value.id).then((res) => {
					console.log(res.data.data)
					const data = res.data.data;
					const from = {};
					const detailList  = []
					from.address = data.province + data.city +  data.county + data.address;
					// console.log(data.province + data.city +  data.county + data.address)
					from.orderNo = data.orderNo
					from.mono = data.mono
					from.adminMono = from.adminMono
					from.phone = data.phone
					from.city = data.province + data.city +  data.county
					from.adminMono = data.adminMono
					from.consignee = data.consignee
					 for(let i = 0; i< data.skuList.length; i++){
						 from.num = data.skuList[i].num;
						 from.title = data.skuList[i].title
						 from.spuTitle = data.skuList[i].spuTitle
						 from.unit = data.skuList[i].unit
					 }
					 detailList.push(from);
					 console.log(detailList)
					 this.excelDown(detailList)
				})
			},
			excelDown(value){
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('../../vendor/Export2Excel.js') //这里根据具体路径来修改
					// console.log(value)
					const tHeader = ["订单编号", '商品名称', '规格', '单位', '配送数量','配送地址','收货人','联系方式','区域划分','客服备注','用户备注']
					const filterVal = ["orderNo", "spuTitle", "title", "unit", "num", "address", "consignee", "phone", "city","mono", "adminMono"]
					const list = value
					const data = this.formatJson(filterVal, list)
					export_json_to_excel(tHeader, data, '订单信息')
				})
			},
			formatJson(filterVal, jsonData) {
				return jsonData.map(v => filterVal.map(j => v[j]))
			},
			// 导出
			download(){
				console.log(this.downloadList)
				if(this.downloadList.gmtStart){
					this.downloadList.gmtStart = this.downloadList.gmtStart.getTime()
				}
				if(this.downloadList.gmtEnd){
					this.downloadList.gmtEnd =  this.downloadList.gmtEnd.getTime()
				}
				
				console.log(this.downloadList)
				queryToExcel(this.downloadList).then((res)=>{
					// console.log(res.data.data)
					if(!res.data.data){
						this.$message.error("没有信息可以打印")
						return;
					}
					let data = res.data.data;
					const detailList  = []
					for(let i = 0; i<data.length;i++){
						const from = {};
						from.address = data[i].province + data[i].city +  data[i].county + data[i].address;
						from.orderNo = data[i].orderNo
						from.mono = data[i].mono
						from.adminMono = data[i].adminMono
						from.phone = data[i].phone
						from.city = data[i].province + data[i].city +  data[i].county
						from.adminMono = data[i].adminMono
						from.consignee = data[i].consignee
						 for(let j = 0; j< data[i].skuList.length; j++){
							 from.num = data[i].skuList[j].num;
							 from.title = data[i].skuList[j].title
							 from.spuTitle = data[i].skuList[j].spuTitle
							 from.unit = data[i].skuList[j].unit
						 }
						 detailList.push(from);
					}
					this.excelDown(detailList)
				})
				.catch((erro) => {
					console.log(erro)
				});
			},
			// 汇总
			downloadAll(){
				let start = ''
				let end = ''
				if(this.downloadList.gmtStart){
					start = this.downloadList.gmtStart.getTime()
				}
				if(this.downloadList.gmtEnd){
					end =  this.downloadList.gmtEnd.getTime()
				}
				statisticsToExcel(start,end).then((res)=>{
					// console.log(res.data.data)
					if(!res.data.data){
						this.$message.error("没有信息可以打印")
						return;
					}
					this.excelDown2(res.data.data)
				})
				.catch((erro) => {
					console.log(erro)
				});
			},
			excelDown2(value){
				require.ensure([], () => {
					const {
						export_json_to_excel
					} = require('../../vendor/Export2Excel.js') //这里根据具体路径来修改
					// console.log(value)
					const tHeader = ['商品名称', 'spuId','规格','skuId', '数量']
					const filterVal = ["spuTitle", "spuId", "skuTitle",'skuId', "num",]
					const list = value
					const data = this.formatJson(filterVal, list)
					export_json_to_excel(tHeader, data, '统计信息')
				})
			},
		},
		created() {
			this.getData()
		}
	}
</script>

<style>
	.order_container {
		width: 100%;
		height: 660px;
		overflow-x: auto;
		overflow-y: auto;
		padding: 20px;
	}

	.order_header>* {
		margin-left: 4px;
	}

	.order_header {
		padding-bottom: 10px;
	}

	.messagae {
		display: inline-block;
		width: 600px;
	}

	.el-table .orange {
		background: rgb(197, 175, 142);
	}

	.el-table .green {
		background: rgb(166, 202, 149);
	}

	.el-table .red {
		background: rgb(201, 143, 143);
	}
</style>
